//
// Created on 2024/6/26.
//
/*
# Copyright (c) 2024 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
*/

#ifndef OHOS_EGLCONTEXT_MANAGE_H
#define OHOS_EGLCONTEXT_MANAGE_H

#include <map>
#include <mutex>
#include <queue>

#include "GLES3/gl32.h"
#include "EGL/egl.h"

#include "rtc_base/thread.h"
#include "ohos_egl_render_context.h"
#include "ohos_yuv_converter.h"

namespace webrtc {

struct EGLContextResource {
    std::shared_ptr<EGLRenderContext> eglContext_;
    EGLContextResource(std::shared_ptr<EGLRenderContext> eglContext): eglContext_(eglContext) {}
};

class OhosEGLContextManager {
public:
    static OhosEGLContextManager& GetInstance() { return ohosEGLContextManage_; }

    std::shared_ptr<EGLContextResource> GetEGLContextResource();
    std::shared_ptr<std::mutex> GetTextureMutex(GLuint texture_id);
    std::shared_ptr<YuvConverter> GetYuvConverter();
    void Clear();

private:
    OhosEGLContextManager() {}
    ~OhosEGLContextManager() {}
    OhosEGLContextManager(OhosEGLContextManager&) = delete;
    OhosEGLContextManager& operator=(const  OhosEGLContextManager&) = delete;
    static OhosEGLContextManager ohosEGLContextManage_;

    std::mutex mutex_;
    std::shared_ptr<EGLContextResource> root_gl_resource_ = nullptr;
    std::mutex texture_mutex_map_mutex_;
    std::map<GLuint, std::shared_ptr<std::mutex>> texture_mutex_map_;
    std::mutex yuv_converter_mutex_;
    std::shared_ptr<YuvConverter> yuv_converter_ = nullptr;
    std::unique_ptr<EGLRenderContext> converter_gl_context_ = nullptr;
    EGLSurface egl_surface_ = EGL_NO_SURFACE;
    rtc::Thread* convert_thread_ = nullptr;
};

} // namespace webrtc
#endif // OHOS_EGLCONTEXT_MANAGE_H
